#include "CClient.h"

int client_thread_func(void *caller)
{
	return ((CClient*) caller)->RunPolling(NULL);
}

void CClient::SetCallbackGUI(IGUICallback* CallbackGUI)
{
	m_pConfigDialog = CallbackGUI;
}

CClient::CClient()
{
	m_bClientstarted = false;
}

CClient::~CClient()
{
	if(m_bClientstarted == false)
		return;
	RakNetworkFactory::DestroyRakPeerInterface(m_pClient);
	SDL_KillThread(m_pPollThread);
}

void CClient::SendChatMessage(const char* str)
{
	
}

int CClient::RunPolling(void* data)
{
	Packet* packet;
	while (1)
	{
		packet=m_pClient->Receive();
		if (packet)
		{
			switch (packet->data[0])
			{
			case ID_REMOTE_DISCONNECTION_NOTIFICATION:
				m_pConfigDialog->UpdateChatWindow("Another client has disconnected.\n");
				break;
			case ID_REMOTE_CONNECTION_LOST:
				m_pConfigDialog->UpdateChatWindow("Another client has lost the connection.\n");
				break;
			case ID_REMOTE_NEW_INCOMING_CONNECTION:
				m_pConfigDialog->UpdateChatWindow("Another client has connected.\n");
				break;
			case ID_CONNECTION_REQUEST_ACCEPTED:
				m_pConfigDialog->UpdateChatWindow("Our connection request has been accepted.\n");
				break;
			case ID_NEW_INCOMING_CONNECTION:
				m_pConfigDialog->UpdateChatWindow("A connection is incoming.\n");
				break;
			case ID_NO_FREE_INCOMING_CONNECTIONS:
				m_pConfigDialog->UpdateChatWindow("The server is full.\n");
				break;
			case ID_DISCONNECTION_NOTIFICATION:
				m_pConfigDialog->UpdateChatWindow("A client has disconnected.\n");
				break;
			case ID_CONNECTION_LOST:
				m_pConfigDialog->UpdateChatWindow("A client lost the connection.\n");
				break;
			default:
				m_pConfigDialog->UpdateChatWindow("Message with identifier %i has arrived.\n");
				break;
			}

			m_pClient->DeallocatePacket(packet);
		}
	}
}

bool CClient::AttemptConnection(const char* ServerIP, unsigned short RemotePort)
{
	bool bRet;

	m_pClient = RakNetworkFactory::GetRakPeerInterface();
	m_pClient->Startup(1,30,&SocketDescriptor(), 1);
	
	bRet = m_pClient->Connect(ServerIP,RemotePort,0,0);
			
	// create a listener thread to listen on the port
	m_pPollThread = SDL_CreateThread(&client_thread_func,this);

	m_bClientstarted = bRet;
	return bRet;
}

